<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- device -->
      <el-col :lg="24" :xs="24">
        <div class="search-container">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="类型" prop="device_type">
              <el-input
                v-model="queryParams.device_type"
                placeholder="请输入名称"
                clearable
                style="width: 200px"
                @keyup.enter="handleQuery"
                @clear="handleQuery"
              />
            </el-form-item>
            <el-form-item label="客户" prop="client">
              <el-input
                v-model="queryParams.client"
                placeholder="请输入客户名称"
                clearable
                style="width: 200px"
                @keyup.enter="handleQuery"
                @clear="handleQuery"
              />
            </el-form-item>
            <el-form-item label="机房">
              <el-select
                v-model="queryParams.room"
                clearable
                placeholder="请选择机房"
                style="width: 200px"
                filterable
                @change="handleChangeRoom"
              >
                <el-option
                  v-for="item in options.machine_rooms"
                  :key="item.id"
                  :value="item.id"
                  :label="item.name"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="机柜" prop="cabinet">
              <el-input
                v-model="queryParams.cabinet"
                placeholder="请输入机柜名称"
                clearable
                style="width: 200px"
                @keyup.enter="handleQuery"
                @clear="handleQuery"
              />
            </el-form-item>
            <el-form-item label="状态">
              <el-select
                v-model="queryParams.status"
                clearable
                placeholder="请选择状态"
                style="width: 200px"
                @change="handleChangeRoom"
              >
                <el-option
                  v-for="item in options.status"
                  :key="item.id"
                  :value="item.value"
                  :label="item.label"
                />
              </el-select>
            </el-form-item>
            <div class="button-group">
              <el-form-item>
                <el-button type="primary" @click="handleQuery"
                  ><i-ep-search />搜索</el-button
                >
                <el-button @click="handleResetQuery">
                  <i-ep-refresh />
                  重置</el-button
                >
              </el-form-item>
            </div>
          </el-form>
        </div>

        <el-card shadow="never" class="table-container">
          <template #header>
            <div class="flex justify-between">
              <div>
                <el-button type="success" @click="openDialog(DialogType.ADD)"
                  ><i-ep-plus />新增</el-button
                >
                <el-button
                  type="danger"
                  :disabled="removeIds.length === 0"
                  @click="handleDelete()"
                  ><i-ep-delete />批量删除</el-button
                >
              </div>
            </div>
          </template>
          <!-- 展示表单 -->
          <el-table
            v-loading="loading"
            :data="pageData"
            border
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="40" align="center" />
            <el-table-column key="id" label="ID" align="center" width="55">
              <template #default="scope">
                {{ scope.$index + 1 }}
              </template>
            </el-table-column>
            <el-table-column label="类型" align="center" prop="device_type" />
            <el-table-column label="厂家" align="center" prop="brand" />
            <el-table-column label="型号" align="center" prop="model" />
            <el-table-column label="所在U位" align="center">
              <template #default="{ row }"> 第{{ row.height }}U </template>
            </el-table-column>
            <el-table-column label="SN" align="center" prop="sn" />
            <el-table-column label="状态" align="center">
              <template #default="scope">
                <el-tag
                  v-if="scope.row.status.value"
                  :type="getStatusType(scope.row)"
                  effect="dark"
                >
                  {{ scope.row.status.value }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="所属客户" align="center">
              <template #default="scope">
                {{ scope.row.client.name }}
              </template>
            </el-table-column>
            <el-table-column label="所属机柜" align="center">
              <template #default="scope">
                {{ scope.row.cabinet.name }}
              </template>
            </el-table-column>
            <el-table-column label="所属机房" align="center">
              <template #default="scope">
                <span
                  class="center-bg"
                  @click="handleClickRoomName(scope.row)"
                  >{{ scope.row.room.name }}</span
                >
              </template>
            </el-table-column>

            <el-table-column
              label="操作"
              fixed="right"
              align="center"
              width="200"
            >
              <template #default="scope">
                <el-button
                  type="primary"
                  link
                  size="small"
                  @click="openDialog(DialogType.EDIT, scope.row)"
                  ><i-ep-edit />编辑</el-button
                >
                <el-button
                  type="primary"
                  size="small"
                  link
                  @click="openDialog(DialogType.DETAIL, scope.row)"
                  ><i-ep-refresh-left />查看</el-button
                >
                <el-button
                  type="primary"
                  link
                  size="small"
                  @click="handleDelete(scope.row.id)"
                  ><i-ep-delete />删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-if="total > 0"
            v-model:total="total"
            v-model:page="queryParams.page"
            v-model:limit="queryParams.pagesize"
            @pagination="handleQuery"
          />
        </el-card>
      </el-col>
    </el-row>

    <!-- 弹窗 -->
    <el-dialog
      v-if="dialog.visible"
      v-model="dialog.visible"
      :title="dialog.title"
      :width="dialog.width"
      append-to-body
      @close="closeDialog"
    >
      <!-- 用户新增/编辑表单 -->
      <el-form
        :inline="true"
        class="demo-form-inline"
        v-if="isAddOrEdit || isDetail"
        ref="userFormRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="客户">
          <el-select
            v-model="formData.client"
            clearable
            placeholder="所属客户"
            :disabled="isDetail"
            style="width: 200px"
            filterable
          >
            <el-option
              v-for="item in options.clients"
              :key="item.id"
              :value="item.id"
              :label="item.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="机房">
          <el-select
            v-model="formData.room"
            clearable
            placeholder="请选择机房"
            :disabled="isDetail"
            style="width: 200px"
            filterable
            @change="handleChangeRoom"
          >
            <el-option
              v-for="item in options.machine_rooms"
              :key="item.id"
              :value="item.id"
              :label="item.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="机柜">
          <el-select
            v-model="formData.cabinet"
            clearable
            placeholder="请选择机柜"
            :disabled="isDetail"
            filterable
            style="width: 200px"
          >
            <el-option
              v-for="item in options.cabinets"
              :key="item.id"
              :value="item.id"
              :label="item.number"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="类型" prop="device_type">
          <el-input
            v-model="formData.device_type"
            autocomplete="off"
            placeholder="请输入类型"
            :disabled="isDetail"
          />
        </el-form-item>
        <el-form-item label="厂家" prop="brand">
          <el-input
            v-model="formData.brand"
            autocomplete="off"
            placeholder="请输入厂家"
            :disabled="isDetail"
          />
        </el-form-item>
        <el-form-item label="型号" prop="model">
          <el-input
            v-model="formData.model"
            autocomplete="off"
            placeholder="输入型号"
            :disabled="isDetail"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="formData.status"
            clearable
            placeholder="请选择状态"
            :disabled="isDetail"
            style="width: 200px"
          >
            <el-option
              v-for="item in options.status"
              :key="item.id"
              :value="item.value"
              :label="item.label"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="U位" prop="height">
          <el-input
            v-model="formData.height"
            autocomplete="off"
            placeholder="输入设备所在U位"
            :disabled="isDetail"
            type="number"
            min="0"
            :validate-event="false"
          />
        </el-form-item>
        <el-form-item label="SN" prop="sn">
          <el-input
            v-model="formData.sn"
            autocomplete="off"
            placeholder="输入SN"
            :disabled="isDetail"
          />
        </el-form-item>
        <el-form-item label="IPMI IP" prop="ipmi_ip">
          <el-input
            v-model="formData.ipmi_ip"
            autocomplete="off"
            placeholder="输入IPMI IP"
            :disabled="isDetail"
          />
        </el-form-item>
        <el-form-item label="IP" prop="ip_address">
          <el-input
            v-model="formData.ip_address"
            autocomplete="off"
            placeholder="输入IP"
            :disabled="isDetail"
        /></el-form-item>
        <el-form-item label="网关" prop="gateway">
          <el-input
            v-model="formData.gateway"
            autocomplete="off"
            placeholder="输入网关"
            :disabled="isDetail"
          />
        </el-form-item>
        <el-form-item label="子网掩码" prop="subnet">
          <el-input
            v-model="formData.subnet"
            autocomplete="off"
            placeholder="输入子网掩码"
            :disabled="isDetail"
          />
        </el-form-item>
        <el-form-item label="VLAN" prop="vlan">
          <el-input
            v-model="formData.vlan"
            autocomplete="off"
            placeholder="输入VLAN"
            :disabled="isDetail"
          />
        </el-form-item>
        <el-form-item label="主IP" prop="main_ip">
          <el-input
            v-model="formData.main_ip"
            autocomplete="off"
            placeholder="输入主IP"
            :disabled="isDetail"
          />
        </el-form-item>
        <el-form-item label="MAC地址" prop="bound_mac">
          <el-input
            v-model="formData.bound_mac"
            autocomplete="off"
            placeholder="输入MAC地址"
            :disabled="isDetail"
          />
        </el-form-item>
        <el-form-item label="内存" prop="memory">
          <el-input
            v-model="formData.memory"
            autocomplete="off"
            placeholder="输入内存"
            :disabled="isDetail"
          />
        </el-form-item>
        <el-form-item label="硬盘" prop="disk">
          <el-input
            v-model="formData.disk"
            autocomplete="off"
            placeholder="输入硬盘"
            :disabled="isDetail"
          />
        </el-form-item>
        <el-form-item label="密码" prop="os_password">
          <el-input
            v-model="formData.os_password"
            autocomplete="off"
            placeholder="输入密码"
            :disabled="isDetail"
          />
        </el-form-item>

        <el-form-item label="备注" prop="notes">
          <el-input
            type="textarea"
            v-model="formData.notes"
            autocomplete="off"
            placeholder="备注"
            :disabled="isDetail"
            style="width: 600px"
          />
        </el-form-item>
      </el-form>

      <!-- 用户导入表单 -->
      <el-form v-else-if="isImport" :model="importData" label-width="100px">
        <el-form-item label="Excel文件">
          <el-upload
            ref="uploadRef"
            action=""
            drag
            accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
            :limit="1"
            :auto-upload="false"
            :file-list="importData.fileList"
            :on-change="handleFileChange"
            :on-exceed="handleFileExceed"
          >
            <el-icon class="el-icon--upload">
              <i-ep-upload-filled />
            </el-icon>
            <div class="el-upload__text">
              将文件拖到此处，或
              <em>点击上传</em>
            </div>
            <template #tip>
              <div>xls/xlsx files</div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <!-- 弹窗底部操作按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button v-if="!isDetail" type="primary" @click="handleSubmit"
            >确 定</el-button
          >
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "Cmdb",
  inheritAttrs: false,
});

import CMDB_DeviceAPI from "@/api/cmdb/device";
import { DevicePageVO, DeviceQuery, DeviceForm } from "@/api/cmdb/device/model";
import { ClientInfo } from "@/api/cmdb/client/model";
import type { UploadInstance, FormInstance } from "element-plus";
import { genFileId } from "element-plus";
import { DialogType } from "@/enums/DialogType";
import { number } from "echarts";
import { client } from "stompjs";

const queryFormRef = ref<FormInstance>(); // 查询表单
const userFormRef = ref<FormInstance>(); // 表单
const uploadRef = ref<UploadInstance>(); // 上传组件

const loading = ref(false); //  加载状态
const removeIds = ref([]); // 删除 用于批量删除
const queryParams = reactive<DevicePageVO>({
  page: 1,
  pagesize: 10,
});
const dateTimeRange = ref("");
const total = ref(0); // 数据总数
const pageData = ref<DevicePageVO[]>(); // 分页数据

const options = ref({
  // status: [] as any[],
  status: {
    id: 0,
    value: number,
    label: "",
  },
  clients: [] as any[],
  machine_rooms: [] as any[],
  cabinets: [] as any[],
});

function getStatusType(row: any) {
  switch (row.status.id) {
    case 1:
      return "primary";
    case 2:
      return "info";
    case 3:
      return "warning";
    default:
      return "danger";
  }
}

// 弹窗对象
const dialog = reactive({
  visible: false,
  type: "number-form",
  width: 800,
  title: "",
});

// 表单数据
const formData = reactive<DeviceForm>({
  device_type: "",
  brand: "",
  model: "",
  height: "",
  sn: "",
  status: "",
  ipmi_ip: "",
  main_ip: "",
  ip_address: "",
  gateway: "",
  client: "",
  cabinet: "",
  room: "",
});

// 导入数据
const importData = reactive({
  // deptId: undefined,
  file: undefined,
  fileList: [],
});

//定义height的属性 不能为空不能小于0
const height = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback(new Error("设备U位不能为空"));
  }
  if (isNaN(value) || value < 0) {
    return callback(new Error("设备U位必须为非负数字"));
  }
  callback();
};

// 校验规则
const rules = reactive({
  device_type: [
    { required: true, message: "设备类型不能为空", trigger: "blur" },
  ],
  brand: [{ required: true, message: "设备厂商不能为空", trigger: "blur" }],
  model: [{ required: true, message: "设备型号不能为空", trigger: "blur" }],
  height: [
    { required: true, message: "设备U位不能为空", trigger: "blur" },
    { validator: height, trigger: "blur" },
  ],
  client: [{ required: true, message: "所属用户不能为空", trigger: "change" }],
  room: [{ required: true, message: "所属机房不能为空", trigger: "change" }],
  cabinet: [{ required: true, message: "所属机柜不能为空", trigger: "change" }],
});
// email: [
//   {
//     pattern: /\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/,
//     message: "请输入正确的邮箱地址",
//     trigger: "blur",
//   },
// ],
// phone: [
//   {
//     pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
//     message: "请输入正确的手机号码",
//     trigger: "blur",
//   },
// ],

const cabinets = ref<any[]>([]);
/** 查询 */
function handleQuery() {
  loading.value = true;
  CMDB_DeviceAPI.getPage(queryParams)
    .then((data) => {
      pageData.value = data.data.data;
      options.value = data.data.options;
      cabinets.value = data.data.options.cabinets;
      options.value.cabinets = [];
      total.value = data.data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}
//选择关联机房
function handleChangeRoom(value: number | string) {
  formData.cabinet = "";
  options.value.cabinets = cabinets.value.filter((item) => {
    return item.room_id == value;
  });
}

/** 查询状态字典 */
// function getDictList() {
//   loading.value = true;
//   CMDB_DeviceAPI.getDictList()
//     .then((data) => {
//       statuOptions.value = data.data.status;
//     })
//     .finally(() => {
//       loading.value = false;
//     });
// }

/** 重置查询 */
function handleResetQuery() {
  queryFormRef.value?.resetFields();
  queryParams.room = undefined;
  queryParams.status = undefined;
  dateTimeRange.value = "";
  queryParams.page = 1;
  handleQuery();
}

/** 行选中 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

function handleClickRoomName(row: DevicePageVO) {
  queryParams.room = row.room; //
  handleQuery();
}

const isAddOrEdit = computed(() => {
  return dialog.type === DialogType.ADD || dialog.type === DialogType.EDIT;
});
const isDetail = computed(() => {
  return dialog.type === DialogType.DETAIL;
});

const isImport = computed(() => {
  return dialog.type === DialogType.IMPORT;
});

/**
 * 打开弹窗
 *
 * @param type 弹窗类型  用户表单：user-form | 用户导入：user-import
 * @param id 用户ID
 */
async function openDialog(type: string, row?: any) {
  dialog.visible = true;
  dialog.type = type;
  switch (dialog.type) {
    case DialogType.ADD:
      dialog.title = "新增";
      break;
    case DialogType.EDIT:
      dialog.title = "修改";
      Object.assign(formData, { ...row });

      formData.status = row?.status?.id;
      formData.client = row?.client?.id;
      formData.room = row?.room?.id; // 机房
      formData.cabinet = row?.cabinet?.id; // 机柜
      options.value.cabinets = cabinets.value.filter((item) => {
        return item.room_id == row?.room?.id;
      });
      break;
    case DialogType.IMPORT:
      // 用户导入弹窗
      dialog.title = "导入";
      dialog.width = 600;
      break;
    case DialogType.DETAIL:
      dialog.title = "查看";
      Object.assign(formData, { ...row });
      formData.status = row?.status?.id;
      formData.client = row?.client?.id;
      formData.room = row?.room?.id; // 机房
      formData.cabinet = row?.cabinet?.id; // 机柜
      options.value.cabinets = cabinets.value.filter((item) => {
        return item.room_id == row?.room?.id;
      });
      break;

    default:
      break;
  }
}

/**
 * 关闭弹窗
 *
 * @param type 弹窗类型  用户表单：user-form | 用户导入：user-import
 */
function closeDialog() {
  dialog.visible = false;
  if (isAddOrEdit.value) {
    formData.device_type = "";
    formData.brand = "";
    formData.model = "";
    formData.height = "";
    formData.sn = "";
    formData.status = "";
    formData.client = "";
    formData.cabinet = "";
    formData.room = "";
    // userFormRef.value?.resetFields();
    // userFormRef.value?.clearValidate();
  } else if (isImport.value) {
    importData.file = undefined;
    importData.fileList = [];
  }
}

/** 表单提交 */
const handleSubmit = useThrottleFn(() => {
  if (isAddOrEdit.value) {
    userFormRef.value?.validate((valid: any) => {
      if (valid) {
        const userId = formData.id;
        loading.value = true;
        if (userId) {
          CMDB_DeviceAPI.update(formData as any)
            .then(() => {
              ElMessage.success("修改成功");
              closeDialog();
              handleResetQuery();
            })
            .finally(() => (loading.value = false));
        } else {
          CMDB_DeviceAPI.add(formData as any)
            .then(() => {
              ElMessage.success("新增成功");
              closeDialog();
              handleResetQuery();
            })
            .finally(() => (loading.value = false));
        }
      }
    });
  } else if (isImport.value) {
    // if (!importData?.deptId) {
    //   ElMessage.warning("请选择部门");
    //   return false;
    // }
    if (!importData?.file) {
      ElMessage.warning("上传Excel文件不能为空");
      return false;
    }
    // Ap1API.import(importData?.deptId, importData?.file).then((data) => {
    //   ElMessage.success("导入用户成功");
    //   closeDialog();
    //   handleResetQuery();
    // });
  }
}, 3000);

/** 删除用户 */
function handleDelete(id?: number) {
  const userIds = [id || removeIds.value].join(",");
  if (!userIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除用户?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(function () {
    CMDB_DeviceAPI.deleteByIds(userIds).then(() => {
      ElMessage.success("删除成功");
      handleResetQuery();
    });
  });
}

/** 下载导入模板 */
// function downloadTemplate() {
//   Ap1API.downloadTemplate().then((response: any) => {
//     const fileData = response.data;
//     const fileName = decodeURI(
//       response.headers["content-disposition"].split(";")[1].split("=")[1]
//     );
//     const fileType =
//       "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8";

//     const blob = new Blob([fileData], { type: fileType });
//     const downloadUrl = window.URL.createObjectURL(blob);

//     const downloadLink = document.createElement("a");
//     downloadLink.href = downloadUrl;
//     downloadLink.download = fileName;

//     document.body.appendChild(downloadLink);
//     downloadLink.click();

//     document.body.removeChild(downloadLink);
//     window.URL.revokeObjectURL(downloadUrl);
//   });
// }

/** Excel文件 Change */
// function handleFileChange(file: any) {
//   importData.file = file.raw;
// }

/** Excel文件 Exceed  */
// function handleFileExceed(files: any) {
//   uploadRef.value!.clearFiles();
//   const file = files[0];
//   file.uid = genFileId();
//   uploadRef.value!.handleStart(file);
//   importData.file = file;
// }

/** 导出用户 */
// function handleExport() {
//   Ap1API.export(queryParams).then((response: any) => {
//     const fileData = response.data;
//     const fileName = decodeURI(
//       response.headers["content-disposition"].split(";")[1].split("=")[1]
//     );
//     const fileType =
//       "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8";

//     const blob = new Blob([fileData], { type: fileType });
//     const downloadUrl = window.URL.createObjectURL(blob);

//     const downloadLink = document.createElement("a");
//     downloadLink.href = downloadUrl;
//     downloadLink.download = fileName;

//     document.body.appendChild(downloadLink);
//     downloadLink.click();

//     document.body.removeChild(downloadLink);
//     window.URL.revokeObjectURL(downloadUrl);
//   });
// }

onMounted(() => {
  handleQuery();
});
</script>

<style lang="scss" scoped>
.center-bg {
  &:hover {
    padding: 20px;
    color: rgb(21 35 227);
    cursor: pointer;
  }
}

.button-group {
  display: flex;
  justify-content: flex-end; /* 将内容对齐到容器的右端 */
}
</style>
